package com.feng.chat.utils;

import com.alibaba.fastjson.JSON;
import com.feng.chat.controller.WebSocketSever;
import com.feng.chat.dto.KeepAlive;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.websocket.Session;
import java.io.IOException;
import java.util.List;
import java.util.Set;


public class GetUserUtil {
    public static Integer getUserId(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        Integer id = JwtUtil.parserToken(token);
        return id;
    }

    /**
     * 检测用户是否在线
     *
     * @param id
     * @return
     */
    public static Integer isOnLine(Integer id) {
        WebSocketSever webSocketSever = WebSocketSever.onLine.get(id);
        if (webSocketSever == null) {
            return 0;
        } else {
            return 1;
        }
    }

    /**
     * 向单人发送单条消息
     *
     * @param message
     * @param receiver_id
     */
    public static void sendMessage(KeepAlive message, Integer receiver_id) {
        WebSocketSever webSocketSever = WebSocketSever.onLine.get(receiver_id);
        Session session = webSocketSever.getSession();
        try {
            session.getBasicRemote().sendText(JSON.toJSONString(message));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 向多人发送多条消息
     *
     * @param keepAlive
     * @param receiver_ids
     */
    public static void sendManyMessage(KeepAlive keepAlive, List<Integer> receiver_ids) {
        receiver_ids.forEach(item -> {
            sendMessage(keepAlive, item);

        });
    }


}
